package com.ai.module.business.service.impl;

import com.ai.module.chat.common.base.ThreadLocalContext;
import com.ai.module.chat.common.constant.FileStringConstant;
import com.ai.module.chat.common.domain.bo.AliUploadBo;
import com.ai.module.chat.common.domain.vo.RiskReason;
import com.ai.module.chat.common.enu.AliFileSource;
import com.ai.module.chat.common.enu.AliyunImageCheck;
import com.ai.module.chat.config.ChatImageBo;
import com.ai.module.chat.config.advice.exception.BusinessException;
import com.ai.module.chat.config.properties.ChatGptProperty;
import com.ai.module.business.domain.entity.BannerRecordEntity;
import com.ai.module.business.domain.req.ImageAnalyzeReq;
import com.ai.module.business.enu.Source;
import com.ai.module.user.domain.entity.UserImageAnalyzeEntity;
import com.ai.module.user.domain.entity.UserImageEntity;
import com.ai.module.user.domain.vo.ImageAnalyzeVo;
import com.ai.module.user.domain.vo.UserLoginInfo;
import com.ai.module.user.mapper.UserImageAnalyzeMapper;
import com.ai.module.user.mapper.UserImageMapper;
import com.ai.module.user.service.UserImageAnalyzeService;
import com.ai.module.chat.util.Base64Util;
import com.ai.module.chat.util.aliyun.AliyunUtil;
import com.ai.module.mj.constant.stringConstant.ReturnCode;
import com.ai.module.mj.service.TranslateService;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.green20220302.models.ImageModerationResponseBody;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static com.ai.module.chat.util.aliyun.AliyunUtil.aliyunProperty;

/**
 * @author: heJinQin
 * @create: 2024-03-10 00:12
 * @description:
 **/
@Slf4j
@Service
public class UserImageAnalyzeServiceImpl extends ServiceImpl<UserImageAnalyzeMapper, UserImageAnalyzeEntity> implements UserImageAnalyzeService {


    @Autowired
    private BannerRecordServiceImpl bannerRecordService;

    @Autowired
    private TranslateService translateService;

    @Autowired
    private UserImageMapper userImageMapper;

    @Override
    public Page<ImageAnalyzeVo> imageAnalyzeList(ImageAnalyzeReq imageAnalyzeReq) {
        String robotId = imageAnalyzeReq.getRobotId();
        int currentPage = imageAnalyzeReq.getPage();
        Page<ImageAnalyzeVo> objectPage = new Page<>(currentPage, imageAnalyzeReq.getSize());
        Page<ImageAnalyzeVo> page = this.baseMapper.imageAnalyzeList(objectPage,
                robotId
        );
        List<ImageAnalyzeVo> recordList = page.getRecords();
        recordList.forEach(
                t -> {
                    String robotContent = t.getRobotContent();
                    if (StringUtils.hasText(robotContent)) {
                        t.setRobotContentList(Arrays.asList(robotContent.split(",")));
                    }
                }
        );
        if (currentPage == 1) {
            Collections.reverse(recordList);
        }
//        page.setRecords(chatContents);
        return page;
    }


    @Override
    public List<String> imageAnalyze(ImageAnalyzeReq imageAnalyzeReq) {
        try {
            String userId = ThreadLocalContext.getUserId();
            String imageBase64 = imageAnalyzeReq.getImageBase64();
            String fileType = imageAnalyzeReq.getFileType();
            String prompt = imageAnalyzeReq.getPrompt();
            String robotId = imageAnalyzeReq.getRobotId();
            //  文字校验
            RiskReason riskReason = AliyunUtil.getRiskReason(prompt);
            Boolean success = riskReason.getSuccess();
            if (!success) {
                String userRisk = String.join(",", riskReason.getRiskWords());
                bannerRecordService.textCheck(userRisk,
                        null,
                        prompt,
                        Source.IMAGE_ANALYZE_PROMPT
                );
                throw new BusinessException("输入内容[" + userRisk + "]违反规则", ReturnCode.FAILURE);
            }
            File file = Base64Util.base2Image(imageBase64, fileType);
            AliUploadBo aliUploadBo = new AliUploadBo();
            UserLoginInfo userLoginInfo = ThreadLocalContext.getUserLoginInfo();
            String projectName = userLoginInfo.getTaskImageUrl(FileStringConstant.IMAGE_ANALYZE, imageAnalyzeReq.getRobotId());

            aliUploadBo.setExpireDate(LocalDateTime.now().plusMonths(6));
            aliUploadBo.setProjectName(projectName);
            String imageUrl = AliyunUtil.uploadOSSFile(file, aliUploadBo);

            checkImageAnalyzeUrl(imageUrl, userId);

            ChatImageBo.OpenaiContent openaiImageContent = new ChatImageBo.OpenaiContent();
            openaiImageContent.setType("image_url");
            openaiImageContent.setImageUrl(new ChatImageBo.ImageUrl(
                    // "https://mrhe-ai-test.oss-cn-shenzhen.aliyuncs.com/test/base64_2.jpg?Expires=1709507206&OSSAccessKeyId=TMP.3KirpZkkDinnAHtccGedGfdF289eyYghCb6hDKPcQKaRoP7tTvVTXxxMem2NnLUiMqhE6nq6HCVoUJxLokkG95B9EkZrXP&Signature=RJsBXNfxaiokyUGT1x9sFqKnh0k%3D"
//                    "https://mrhe-ai-test.oss-cn-shenzhen.aliyuncs.com/test/base64_2.jpg?Expires=1709602258&OSSAccessKeyId=TMP.3KgtzQVTXYQZSc6J5bgSPdToy6BeBCoNxgL4S7y8BQ9Pc6p9HDBfGguMxpPbmLK6939CL7HECBpqZLVDoSPtgk7gq5XzgL&Signature=w1ew7E3tT2JolKZsBe%2FOaqcHkmE%3D"
                    imageUrl
            ));
            List<String> realContentList = aIImageAnalyzeContent(prompt, openaiImageContent);
            UserImageAnalyzeEntity imageAnalyze = new UserImageAnalyzeEntity();
            imageAnalyze.setPrompt(prompt);
            imageAnalyze.setUserId(userId);
            imageAnalyze.setRobotId(robotId);
            imageAnalyze.setFilePath(imageUrl);
            imageAnalyze.setRobotContent(String.join(",", realContentList));
            save(imageAnalyze);
            log.info("图片分析结果[{}]", realContentList);
            String bucketName = aliyunProperty.getOssBucketName();
            // 进行数据入库
            UserImageEntity userImage = new UserImageEntity();
            userImage.setExpireTime(aliUploadBo.getExpireDate());
            userImage.setBucketName(bucketName);
            userImage.setUserId(userId);
            userImage.setImageSource(AliFileSource.IMAGE_ANALYZE);
            userImage.setFilePath(imageUrl);
            userImage.setScalePath(imageUrl);
            userImage.setBusinessId(imageAnalyze.getUuid());
            userImageMapper.insert(userImage);
            // 设置用户 对话记录
            return realContentList;
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("用户图片描述异常[{}]", ex.getMessage());
            throw new BusinessException("服务异常,请待会儿再试", ReturnCode.FAILURE);
        }


    }

    @Autowired
    private ChatGptProperty chatGptProperty;

    @Override
    public List<String> aIImageAnalyzeContent(String prompt,
                                              ChatImageBo.OpenaiContent openaiImageContent) {
        String Url = "https://api.openai.com/v1/chat/completions";
        ChatImageBo.OpenaiContent openaiContent = new ChatImageBo.OpenaiContent();
        openaiContent.setType("text");
        // 获取用户数据
        String userContent = translateService.translateToEnglish(prompt);
        openaiContent.setText(userContent);
        ArrayList<ChatImageBo.OpenaiContent> openaiContents = new ArrayList<>();
        openaiContents.add(openaiContent);
        openaiContents.add(openaiImageContent);
        ChatImageBo chatImageBo = new ChatImageBo();
        chatImageBo.setModel(chatGptProperty.getPicModel4());
        ChatImageBo.ChatGptMessage chatGptMessage = new ChatImageBo.ChatGptMessage();
        chatImageBo.setMessages(Collections.singletonList(chatGptMessage));
        chatGptMessage.setContent(openaiContents);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(chatGptProperty.getToken());
//        headers.set(HttpHeaders.AUTHORIZATION, "Bearer " + chatGptProperty.getVersion()); // 替换 YOUR_API_KEY 为你的 API 密钥

        HttpEntity<String> entity = new HttpEntity<>(JSONObject.toJSONString(chatImageBo), headers);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<JSONObject> response = restTemplate.postForEntity(Url, entity, JSONObject.class);
        HttpStatus statusCode = response.getStatusCode();
        List<String> realContentList = new ArrayList<>();
        if (statusCode == HttpStatus.OK) {
            JSONObject responseBody = response.getBody();
            JSONArray choices = responseBody.getJSONArray("choices");
            choices.forEach(choice -> {
                JSONObject choiceJson = JSONObject.parseObject(JSONObject.toJSONString(choice));
                String realContent = choiceJson.getJSONObject("message").getString("content");
                realContentList.add(translateService.translateToChinese(realContent));
            });
        }
        return realContentList;
    }

    private void checkImageAnalyzeUrl(String imageUrl, String userId) throws Exception {
        ImageModerationResponseBody.ImageModerationResponseBodyDataResult result = AliyunUtil.doRealCheckImage(imageUrl);
        String bannerLabel = result.getLabel();
        // 图片审核
        if (StringUtils.hasText(bannerLabel)) {
            BannerRecordEntity bannerRecord = new BannerRecordEntity();
            String desc = AliyunImageCheck.getDescByName(bannerLabel);
            bannerRecord.setRule(desc);
            bannerRecord.setBusinessId(null);
            bannerRecord.setOriginalRule(bannerLabel);
            bannerRecord.setBusinessContent(imageUrl);
            bannerRecord.setUserId(userId);
            bannerRecord.setSource(Source.IMAGE_ANALYZE_IMAGE);
            bannerRecord.setConfidence(result.getConfidence());
            bannerRecordService.save(bannerRecord);
            throw new BusinessException(desc.split("。")[0], ReturnCode.FAILURE);
        }
    }

}